/* Application which uses
   (1) Oracle Thin JDBC Driverto connect to the database
   (2) Access result meta data (column names, types and etc.
*/
import java.sql.* ;
import java.net.* ;

public class DBAccess {
	
	public static void main(String args[]) {
//		DriverManager.setLogStream() ;
		String url = "jdbc:oracle:thin:@cheval:1521:TEST";
		String usr = "scott" ;
		String pwd = "tiger" ;
		System.out.println( "Data From Employee Database" );

		try {
			DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

		} catch(SQLException e) {
			System.err.print("ClassNotFoundException: ");
			System.err.println(e.getMessage());
		}

		try {
			Connection cnn = DriverManager.getConnection(url, usr, pwd) ;
			Statement stmt = cnn.createStatement() ;
			ResultSet rs = stmt.executeQuery("SELECT * FROM Emp") ;

			ResultSetMetaData mdata = rs.getMetaData();
			int colCnt = mdata.getColumnCount();
			int [] widthArr = new int[colCnt];
			for ( int i = 1; i <= colCnt; i ++ ) {
				widthArr[i-1] = mdata.getColumnDisplaySize(i);
				switch( mdata.getColumnType(i) ) {
				   case Types.NUMERIC: widthArr[i-1] = 10; break;
				   case Types.DECIMAL: widthArr[i-1] = 10; break;
				   case Types.DATE: widthArr[i-1] = 10; break;
				   case Types.TIME: widthArr[i-1] = 10; break;
				   case Types.TIMESTAMP: widthArr[i-1] = 10; break;
				}
			}

			//------------ Print table heading ---------------------------
			for (int i = 1; i <= colCnt; i ++) 
				System.out.print(ScreenIO.expandString(widthArr[i-1], mdata.getColumnName(i)) + " "); 
			System.out.println();
			for (int i = 1; i <= colCnt; i ++) 
				System.out.print(ScreenIO.makeString('=', widthArr[i-1]) + " "); 
			System.out.println();
			//-------------------------------------------------------------
		

			while ( rs.next() ) {
				for (int i = 1; i <= colCnt; i ++)
					// call expandString(s, len) will do left-alignment.
					System.out.print( ScreenIO.expandString(widthArr[i-1], 
							ScreenIO.capitalize(rs.getString(i)) )+ " ");
				System.out.println();
			}
			stmt.close();
			cnn.close();
		} catch( SQLException e ) { System.out.println(e.toString()) ; }
			
	}
}
